package com.budwk.app.sqfw.services.customservice.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.budwk.app.common.config.AppException;
import com.budwk.app.sqfw.component.CommunityStreetComponent;
import com.budwk.app.sqfw.constants.CommonConstants;
import com.budwk.app.sqfw.constants.DictConstants;
import com.budwk.app.sqfw.enums.SupportBusinessTypeEnum;
import com.budwk.app.sqfw.models.Sqfw_formSummary_new;
import com.budwk.app.sqfw.services.customservice.SqfwBaseDataSearchForAdminService;
import com.budwk.app.sqfw.vo.SqfwCustomForAdminCommonVO;
import com.budwk.app.sqfwV2.dto.entity.SqfwShopsBaseInfo;
import com.budwk.app.sqfwV2.service.ShopsBaseInfoService;
import com.budwk.app.sys.models.Sys_user;
import com.budwk.app.sys.services.SysUserService;
import com.budwk.app.util.adminUtils.CommonCheckUtils;
import com.budwk.starter.common.page.Pagination;
import com.budwk.starter.common.result.ResultCode;
import com.budwk.starter.security.utils.SecurityUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.nutz.dao.Cnd;
import org.nutz.dao.sql.Criteria;
import org.nutz.dao.util.cri.SqlExpressionGroup;
import org.nutz.dao.util.cri.Static;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Strings;

import java.util.*;

/**
 * @program: dfxy-community-dev
 * @description: 社区服务基础数据服务实现
 * @author: LJT
 * @create: 2024-02-29 14:43
 **/
@IocBean
@Slf4j
public class SqfwBaseDataSearchForAdminServiceImpl implements SqfwBaseDataSearchForAdminService {

    @Inject
    private SysUserService sysUserService;

    @Inject
    private ShopsBaseInfoService shopsBaseInfoService;

    @Inject
    private CommunityStreetComponent communityStreetComponent;


    @Override
    public Pagination list(SqfwCustomForAdminCommonVO bean) {
        long startTime = System.currentTimeMillis();
        // 构造查询条件
        Criteria criteria = buildQueryCond(bean);
        Pagination pagination = shopsBaseInfoService.listPage(bean.getPageNo(), bean.getPageSize(), criteria);
        List<SqfwShopsBaseInfo> queryList = pagination.getList(SqfwShopsBaseInfo.class);
        if (ObjectUtil.isNotEmpty(queryList)) {
            List<SqfwCustomForAdminCommonVO> finalCommonVOList = new ArrayList<SqfwCustomForAdminCommonVO>();
            // 字典列表查询
            Map<String, String> dictCodesMap = CommonCheckUtils.getDictInfoMaps(Arrays.asList(
                    DictConstants.MAIN_BUSINESS_SCOPE,
                    DictConstants.USAGE_FIRE_ELECTRICITY,
                    DictConstants.RESIDENTS_FORM,
                    DictConstants.MAIN_BUSINESS_SCOPE_SAFETY));
            queryList.forEach(source -> {
                SqfwCustomForAdminCommonVO target = new SqfwCustomForAdminCommonVO();
                BeanUtil.copyProperties(source, target);
                if (ObjectUtil.isNotEmpty(target.getMainBusinessScope())) {
                    String mainBusinessScope = target.getMainBusinessScope();
                    String[] mainBusinessScopes = mainBusinessScope.split(",");
                    StringBuffer sb = new StringBuffer();
                    for (String mainBusiness : mainBusinessScopes) {
                        String mainBusinessTmp = dictCodesMap.get(mainBusiness);
                        if (StringUtils.isEmpty(mainBusinessTmp)) {
                            continue;
                        }
                        sb.append(mainBusinessTmp).append(",");
                    }
                    if (ObjectUtil.isNotEmpty(sb)) {
                        mainBusinessScope = sb.substring(0, sb.length() - 1);
                    }
                    target.setMainBusinessScopeName(mainBusinessScope);
                }
                // 业务类型枚举转换
                if (ObjectUtil.isNotEmpty(target.getServiceType())) {
                    String serviceType = target.getServiceType();
                    String[] serviceTypes = serviceType.split(",");
                    StringBuffer sb = new StringBuffer();
                    for (String type : serviceTypes) {
                        String typeTmp = SupportBusinessTypeEnum.getNameByCode(type);
                        if (StringUtils.isEmpty(typeTmp)) {
                            continue;
                        }
                        sb.append(typeTmp).append(",");
                    }
                    if (ObjectUtil.isNotEmpty(sb)) {
                        serviceType = sb.substring(0, sb.length() - 1);
                    }
                    target.setServiceTypeName(serviceType);
                }
                finalCommonVOList.add(target);
            });
            pagination.setList(finalCommonVOList);
        }
        log.info("SqfwBaseDataSearchForAdminServiceImpl-list 耗时: {}ms", System.currentTimeMillis() - startTime);
        return pagination;
    }

    private Criteria buildQueryCond(SqfwCustomForAdminCommonVO bean) {
        Criteria cri = Cnd.cri();
        SqlExpressionGroup criSql = cri.where();

        // 组装查询条件
        if (StringUtils.isNotBlank(bean.getPageOrderName()) && Strings.isNotBlank(bean.getPageOrderBy())) {
            if (bean.getPageOrderBy().equals(CommonConstants.ASC)) {
                cri.getOrderBy().asc(bean.getPageOrderName());
            }
            if (bean.getPageOrderBy().equals(CommonConstants.DESC)) {
                cri.getOrderBy().desc(bean.getPageOrderName());
            }
        } else {
            cri.getOrderBy().desc(Sqfw_formSummary_new::getFillDate);
        }

        Sys_user sysUser = sysUserService.fetch(SecurityUtil.getUserId());
        if (ObjectUtils.isEmpty(sysUser)) {
            throw new AppException(ResultCode.USER_NOT_FOUND.getMsg());
        }
        // 区域5级检查
        CommonCheckUtils.checkAreaRange(criSql);
        // 省
        if (StringUtils.isNotBlank(bean.getProvince()) && !CommonCheckUtils.ZHISHU.equals(bean.getProvince())) {
            criSql.andEquals(SqfwCustomForAdminCommonVO::getProvince, bean.getProvince());
        }
        // 市
        if (StringUtils.isNotBlank(bean.getCity()) && !CommonCheckUtils.ZHISHU.equals(bean.getCity())) {
            criSql.andEquals(SqfwCustomForAdminCommonVO::getCity, bean.getCity());
        }
        // 区
        if (StringUtils.isNotBlank(bean.getDistrict()) && !CommonCheckUtils.ZHISHU.equals(bean.getDistrict())) {
            criSql.andEquals(SqfwCustomForAdminCommonVO::getDistrict, bean.getDistrict());
        }
        // 街道
        if (StringUtils.isNotBlank(bean.getCounty()) && !CommonCheckUtils.ZHISHU.equals(bean.getCounty())) {
            criSql.andEquals(SqfwCustomForAdminCommonVO::getCounty, bean.getCounty());
        }
        // 时间
        if (ObjectUtil.isNotEmpty(bean.getQueryStartTime()) && ObjectUtil.isNotEmpty(bean.getQueryEndTime())) {
            criSql.andBetween(SqfwShopsBaseInfo::getFillDate,
                    communityStreetComponent.handleStartQueryTime(bean.getQueryStartTime()),
                    communityStreetComponent.handleEndQueryTime(bean.getQueryEndTime()));
        }
        // 辖区
        if (StringUtils.isNotBlank(bean.getCommunity()) && !CommonCheckUtils.ZHISHU.equals(bean.getCommunity())) {
            criSql.andEquals(SqfwShopsBaseInfo::getCommunity, bean.getCommunity());
        }
        // 全局搜索
        if (StringUtils.isNotEmpty(bean.getQueryAll())) {
            SqlExpressionGroup placeName = Cnd.exps(new Static("place_name like '%" + bean.getQueryAll() + "%'"));
            SqlExpressionGroup businessLicenseName = Cnd.exps(new Static("business_license_name like '%" + bean.getQueryAll() + "%'"));
            SqlExpressionGroup socialCreditCode = Cnd.exps(new Static("social_credit_code like '%" + bean.getQueryAll() + "%'"));
            SqlExpressionGroup address = Cnd.exps(new Static("address like '%" + bean.getQueryAll() + "%'"));
            SqlExpressionGroup detailAddress = Cnd.exps(new Static("detail_address like '%" + bean.getQueryAll() + "%'"));
            SqlExpressionGroup operator = Cnd.exps(new Static("operator like '%" + bean.getQueryAll() + "%'"));
            SqlExpressionGroup community = Cnd.exps(new Static("community like '%" + bean.getQueryAll() + "%'"));
            SqlExpressionGroup operatorTelephone = Cnd.exps(new Static("operator_telephone like '%" + bean.getQueryAll() + "%'"));
            criSql.and(placeName.or(businessLicenseName).or(socialCreditCode).or(address).or(detailAddress).or(operator).or(community).or(operatorTelephone));
        }

        // 限制仅查 社会治安 和 安全排查 数据， 存在这种数据 "safety_check,public_security"
        SqlExpressionGroup safetySecurity = Cnd.exps(new Static("service_type like '%" + SupportBusinessTypeEnum.PUBLIC_SECURITY.getCode() + "%'"));
        SqlExpressionGroup publicSecurity = Cnd.exps(new Static("service_type like '%" + SupportBusinessTypeEnum.SAFETY_CHECK.getCode() + "%'"));
        criSql.and(safetySecurity.or(publicSecurity));

        // 场所类型
        if (StringUtils.isNotBlank(bean.getType())) {
            criSql.andEquals(SqfwShopsBaseInfo::getType, bean.getType());
        }
        // 场所名称
        if (StringUtils.isNotBlank(bean.getPlaceName())) {
            criSql.andEquals(SqfwShopsBaseInfo::getPlaceName, bean.getPlaceName());
        }
        // 场所地址
        if (StringUtils.isNotBlank(bean.getAddress())) {
            criSql.andEquals(SqfwShopsBaseInfo::getAddress, bean.getAddress());
        }
        // 场所地址
        if (StringUtils.isNotBlank(bean.getDetailAddress())) {
            criSql.andEquals(SqfwShopsBaseInfo::getDetailAddress, bean.getDetailAddress());
        }
        // 经营者
        if (ObjectUtil.isNotEmpty(bean.getOperator())) {
            criSql.andEquals(SqfwShopsBaseInfo::getOperator, bean.getOperator());
        }
        // 经营者电话
        if (ObjectUtil.isNotEmpty(bean.getOperatorTelephone())) {
            criSql.andEquals(SqfwShopsBaseInfo::getOperatorTelephone, bean.getOperatorTelephone());
        }
        // 场所经营范围
        if (ObjectUtil.isNotEmpty(bean.getMainBusinessScope())) {
            criSql.andEquals(SqfwShopsBaseInfo::getMainBusinessScope, bean.getMainBusinessScope());
        }
        // 业务类型, 存在这种数据 "safety_check,public_security"
        if (ObjectUtil.isNotEmpty(bean.getServiceType())) {
            String[] serviceTypes = bean.getServiceType().split(",");
            StringBuffer sb = new StringBuffer();
            for (String type : serviceTypes) {
                sb.append(" (service_type LIKE '%").append(type).append("%') ").append(" OR");
            }
            if (ObjectUtil.isNotEmpty(sb) && sb.toString().endsWith("OR")) {
                criSql.and(new Static("(" + sb.substring(0, sb.length() - 2) + ")"));
            }
        }
        return cri;
    }
}
